import React, {Component} from 'react';
import Select from "react-select";
import {connect} from 'react-redux'
import {getProjectList} from '../../redux/actions/projects'
import '../../assets/scss/components/general/selectProject.scss'

class SelectProject extends Component {
  requestParams = {
    includes: "group,spotify,owner",
    fields: "projects.name,projects.id",
    orderBy: "-id",
  }

  constructor(props) {
    super(props);
    this.state = {
      selectOptions: [],
      value: ''
    }
  }

  getProjectList() {
    if (this.props.projectList.length) {
      this.setState({
        selectOptions: this.props.projectList
          .filter(project => !this.props.onlyOwners || project.owner.id === this.props.owner)
          .map(item => ({
            ...item,
            value: item.id,
            label: item.name,
            group_id: item.group.id
          }))
      })
    }
  }

  componentDidMount() {
    if (this.props.owner) this.requestParams['owner'] = this.props.owner
    if (this.props.isGetProjects)
      this.props.getProjectList(this.requestParams)

    this.getProjectList()
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (prevProps.projectList !== this.props.projectList) {
      this.getProjectList()
    }
  }

  handleChange = selectedOption => {
    this.props.onChange(selectedOption)
    this.setState({
      value: selectedOption
    })
  };

  render() {

    return (
      <React.Fragment>
        <Select
          className={`input-dark-bg ${this.props.className} ${this.props.required ? 'is-invalid input-invalid' : ''}`}
          maxMenuHeight={this.props.maxMenuHeight}
          classNamePrefix="dark_select"
          value={this.state.value || this.props.selectedProject}
          options={this.state.selectOptions}
          onChange={this.handleChange}
          name="color"
        />
        <div className="invalid-feedback">Выберите проект</div>
      </React.Fragment>
    )
  }
}


export default connect(null, {getProjectList})(SelectProject)
